﻿using System.Windows;
using System.Windows.Shapes;

namespace DynamicGeometry
{
    public abstract class PointBase : CoordinatesShapeBase<Shape>, IPoint
    {
        public override string GenerateFigureName()
        {
            return GenerateNewPointName();
        }

        public string GenerateNewPointName()
        {
            var alphabet = Settings.Instance.PointAlphabet;
            for (int i = 0; ; i++)
            {
                string number = i.ToString();
                if (i == 0)
                {
                    number = "";
                }
                foreach (var letter in alphabet)
                {
                    var candidate = letter.ToString() + number;
                    if (NameAvailable(candidate))
                    {
                        return candidate;
                    }
                }
            }
        }

        bool NameAvailable(string name)
        {
            if (Drawing == null)
            {
                return true;
            }
            return !Drawing.Figures.Contains(name);
        }

        protected override int DefaultZOrder()
        {
            return (int)ZOrder.Points;
        }

        protected override Shape CreateShape()
        {
            return Factory.CreatePointShape();
        }

        public override void UpdateVisual()
        {
            Shape.CenterAt(ToPhysical(Coordinates));
        }

        public virtual double X
        {
            get
            {
                return Coordinates.X;
            }
            set
            {
                Coordinates = Coordinates.SetX(value);
            }
        }

        public virtual double Y
        {
            get
            {
                return Coordinates.Y;
            }
            set
            {
                Coordinates = Coordinates.SetY(value);
            }
        }

        double PointSize
        {
            get
            {
                return Shape.ActualWidth / 2;
            }
        }

        public override IFigure HitTest(Point point)
        {
            if (Shape != null && !Shape.IsHitTestVisible)
            {
                return null;
            }
            double sensitivity = CursorTolerance + ToLogical(PointSize);
            if (point.X >= Coordinates.X - sensitivity
                && point.X <= Coordinates.X + sensitivity
                && point.Y >= Coordinates.Y - sensitivity
                && point.Y <= Coordinates.Y + sensitivity)
            {
                return this;
            }
            return null;
        }
    }
}